<?php
namespace App\Http\Controllers\Tools;
use App\Common\Jpush;
use App\Common\TLSSigAPI;
use App\Http\Controllers\Weixin\WeixinServiceController;
use App\Models\V1\ChapterModel;
use App\Models\V1\CompanyModel;
use App\Models\V1\DrpModel;
use App\Models\V1\MemberModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Service\Region;
use Excel;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;
use App\Common\MobileMassege;
use App\Common\Http;
use EasyWeChat\Payment\Order;
use Illuminate\Support\Facades\Redis;


class CreateData{
    public $count = 0;

    /**
     * 移动会员
     * */
    public function move_member(){
        $time   = date_time();
        $sql = "INSERT INTO company_user (
                  company_id,
                  department_id,
                  user_id,
                  job,
                  is_delete,
                  release_time,
                  add_time
                  )
                SELECT company_id,department_id,UserID,job,0,'{$time}','$time'
                FROM  memberinfo WHERE DeleteMark=1 AND company_id > 0";
        DB::insert($sql);
        return 'ok';
    }



    //把以前存在公司里面的工作和部门都移到读书会成员表里面去
    public function move_job_and_department(){

        DB::table('memberinfo')->where('DeleteMark',1)->where('company_id',"<>",0)->chunk(1000,function($users){

            $time   = date_time();
            foreach($users as $user){
                $count = DB::table('company_user')->where('user_id',$user->UserID)->where('company_id',$user->company_id)->first();
                if($count){
                    continue;
                }
                $sql = "INSERT INTO company_user (
                  company_id,
                  department_id,
                  user_id,
                  job,
                  is_delete,
                  release_time,
                  add_time
                  )
                SELECT company_id,department_id,UserID,job,0,'{$time}','$time'
                FROM  memberinfo WHERE UserID = $user->UserID";
                DB::insert($sql);
            }

        });
        return ['ok'];
    }



    public function member_exists_readparty_bu_no_company(){
        $time   = date_time();

        $SQL = "
                INSERT INTO company_user(
                 company_id,
                  department_id,
                  user_id,
                  job,
                  is_delete,
                  release_time,
                  add_time
                )
                SELECT
	                  b.company_id,0,a.user_id,'',0,'{$time}','{$time}'
                FROM
	                  read_party_member a
                LEFT JOIN read_party b ON b.ReaParID = a.read_party_id
                LEFT JOIN company_user d ON d.user_id = a.user_id AND d.company_id = b.company_id
                WHERE b.company_id > 0
                  AND d.company_id IS NULL  AND a.is_employee = 1";

        DB::insert($SQL);
        return ['ok'];
    }




    /**
     * 入口方法
     * */
    public function methodPort(Request $request){

        $method = $request->input('method');
        return $this->$method($request);
    }



    /**
     * clo关系图 以下三个方法连用
     *
     * */
    public function getCloList(){

        $prisidents = $this->get_all_prisidents();
        $prisidentIds = [];
        $chapters   = [];

        foreach($prisidents as $p){

            array_push($prisidentIds,$p->DRPID);
            array_push($chapters,$p->chapter_name);
        }

        $topClos = $this->get_child_clo(0,$prisidentIds,$chapters);
        $content = $this->createHtml($topClos);
        return view('other/clos',['content'=>$content]);
        //return [$topClos];
    }

    public function get_child_clo($pid,$prisidents,$chapters){

        $cloList = DB::table('memberdrp as a')
            ->leftJoin('memberinfo as b','b.MemNumber','=','a.MemNumber')
            ->where('a.ParentID',$pid)
            ->where('a.DeleteMark',1)
            ->where('b.DeleteMark',1)
            ->where('a.DRPLevel',1)
            ->whereNotNull('b.YourName')
            ->select('a.DRPID','b.UserName','b.YourName','b.UserID')
            ->get();


            foreach($cloList as $key => $clo){

                $clo->chapterName = false;
                if($clo->UserName){

                    $clo->child = $this->get_child_clo($clo->DRPID,$prisidents,$chapters);
                    $p =  array_search($clo->DRPID,$prisidents);
                    if( $p !== false){
                        $clo->chapterName = $chapters[$p];
                        //如果是会长  检查是发起人还是会长
                        $info = DB::table('chapter_prisident')
                            ->where('user_id',$clo->UserID)
                            ->where("is_delete",0)
                            ->first();
                        $clo->prisidentType = $info->prisident_type === "Z"?"发起人":"会长";
                    }
                }else{

                    $cloList->child = [];
                }
            }
            $this->count++;
            return $cloList;
    }

    private function createHtml($data){
        $content = "";
        $content .="<table>";

        foreach($data as $clo){
            $content .= "<tr>";
            $content .= "<td>{$clo->DRPID}</td>";
            if($clo->chapterName){
                $content .= "<td>{$clo->YourName}<br/><span style='color:red;'>{$clo->chapterName}{$clo->prisidentType}</span> </td>";
            }else{
                $content .= "<td>{$clo->YourName}</td>";
            }
            $content .= "<td>{$clo->UserName}</td>";


            $content .= "<td>";
            if(count($clo->child)>0){
                $content .= "<table>";
                $content .= "<tr><th>下级学习官</th></tr>";
                $temp = $this->createHtml($clo->child);
                $content .= "<tr><td>{$temp}</td></tr>";
                $content .= "</table>";
            }
            $content .= "</td>";
            $content .= "</tr>";
        }
        $content.="</table>";
        return $content;
    }



    //获得用户的城市信息
    public function get_member_city(Request $request){
        ignore_user_abort();
        set_time_limit(0);
        $interval       = 1;
        $memberModel    = new MemberModel();
        $userId         = $request->input('userId',0);
        if($userId > 0 )
        {
            $userId = $userId - 1;
        }
        else
        {
            $info = DB::table('system_log')->where('id',1)->first();
            $userId = $info->value;
        }

        $regionService = new Region();

        do{
            //获取用户信息
            $memberInfo = DB::table('memberinfo')
                ->where('UserID','>',$userId)
                ->where('States',1)
                ->where('DeleteMark',1)
                ->where('city',0)
                ->orderBy('UserID')
                ->first();

            DB::table('system_log')
                ->where('id',1)
                ->update(['value'=>$userId+1]);


            if(!$memberInfo){
                die('end');
            }


            $mobile = $memberInfo->UserName;
            $userId = $memberInfo->UserID;

            if(!preg_match('/1\d{10}/',$mobile)){

                $userId++;
                continue;
            }



            //获取用户城市信息
            $cityInfo = $regionService->get_mobile_city_info($mobile);

            if(!$cityInfo){
                $userId++;
                continue;
            }

            //验证手机号码

            if($cityInfo){
                $cityId = $cityInfo->region_id;
                $memberModel->update_member_info(['UserID'=>$userId,'city'=>$cityId]);
            }else{
                mylogger('cityerror-'.$memberInfo->UserName);

            }
            $userId++;

            sleep($interval);

        }while(true);
    }


    //请求手机号
    public function request_mobile(){
        return view('other/mobile');
    }



    //根据parentId线索 向下搜索  设置子学习官的IDTree
    public function set_clo_child($pid = 0){

        $parents = $this->find_child($pid);

        foreach($parents as $clo){

            $idTree = $clo->IDTree;
            $pid    = $clo->DRPID;
            //修改子学习官IDtree
            $sql = "UPDATE memberdrp
                    SET IDTree = CONCAT('{$idTree}',DRPID,'.')
                    WHERE ParentID = $pid";

            //exit($sql);
            DB::update($sql);
            $this->set_clo_child($pid);
        }
    }


    public function find_child($pid){
        $info = DB::table('memberdrp')->where('parentID',$pid)
            ->where('DeleteMark',1)
            ->where('DRPLevel',1)
            ->get();
        return $info;
    }

    //获得所有会长
    private function get_all_prisidents(){

        $sql = "SELECT a.*,d.DRPID,b.YourName,k.chapter_name
                FROM chapter_prisident a
                LEFT JOIN memberinfo b ON  b.UserID = a.user_id
                LEFT JOIN memberdrp  d ON  d.MemNumber = b.MemNumber
                LEFT JOIN chapter    k ON  k.chapter_id = a.chapter_id
                WHERE a.is_delete = 0
                AND  b.DeleteMark = 1
                AND  d.DeleteMark = 1
                ORDER BY k.chapter_id
                ";

        $prisidents = DB::select($sql);
        return $prisidents;
    }




    //列出分会下面的学习官
    public function find_chapter(Request $request){

        //1.列出分会下面的会长
        $prisidents = $this->get_all_prisidents();
        $prisidentIds = [];
        foreach($prisidents as $key => $p){

            if($p->DRPID == 7668){
                $p->DRPID = 0;
            }
            array_push($prisidentIds,$p->DRPID);
        }

        foreach($prisidents as $p){

            $chapterId      = $p->chapter_id;
            $chapterName    = $p->chapter_name;
            $drpId = $p->DRPID;
            $p->clos = $this->get_local_chapter_clo($drpId,$prisidentIds);
        }




        return view('other/chapter-clos',['chapters'=>$prisidents]);

        //导出表格
        $clos = [];
        $excel = $request->input('excel',0);
        if($excel == 1){
            $data = [];
            foreach($clos as $clo){
                $d = [$clo->UserName,$clo->YourName,$clo->chapter_name,$clo->city];
                array_push($data,$d);
            }

            Excel::create('学习官区域表',function($excel) use ($data){  //创建一个文件
                $excel->sheet('score', function($sheet) use ($data){ //创建一张表
                    $sheet->rows($data);
                });
            })->export('xls');
            exit;
        }
    }



    //将学习官与分会的关系写入数据库
    public function insert_chapter_clo(Request $request){
        $inser = $request->input('insert',0);
        if($inser == 0){
            echo "if you need insert ,please change url to \"?method=insert_chapter_clo&insert=1\"";
            exit;
        }

        //1.列出分会下面的会长
        $prisidents = $this->get_all_prisidents();
        $prisidentIds = [];
        foreach($prisidents as $key => $p){

            if($p->DRPID == 7668){
                $p->DRPID = 0;
            }
            array_push($prisidentIds,$p->DRPID);
        }

        $dateTime   = date_time();
        foreach($prisidents as $p){
            $chapterId      = $p->chapter_id;
            $chapterName    = $p->chapter_name;
            $drpId = $p->DRPID;
            $clos = $this->get_local_chapter_clo($drpId,$prisidentIds);
            $data = [];
            foreach($clos as $clo){
                array_push($data,[
                    'chapter_id'    => $chapterId,
                    'user_id'       => $clo->UserID,
                    'is_delete'     => 0,
                    'total_money'   => 0,
                    'payed_money'   => 0,
                    'surplus_money' => 0,
                    'add_time'      => $dateTime
                ]);
            }

            array_push($data, [
                'chapter_id'    => $chapterId,
                'user_id'       => $p->user_id,
                'is_delete'     => 0,
                'total_money'   => 0,
                'payed_money'   => 0,
                'surplus_money' => 0,
                'add_time'      => $dateTime
            ]);
            DB::table('chapter_drp')->insert($data);
        }

    }




    //获得某学习官下面的所属他的分会的学习观
    private function get_local_chapter_clo($drpId,$prisidentIds){

        $sql = "SELECT a.DRPID,b.YourName,b.UserName,b.UserID
                FROM memberdrp a
                LEFT JOIN memberinfo b ON  b.MemNumber = a.MemNumber
                WHERE a.ParentID = $drpId
                AND   a.DeleteMark = 1
                AND   a.DRPLevel = 1
                AND   b.DeleteMark = 1";
        $clos = DB::select($sql);
        $data = [];
        foreach($clos as $clo){
            if(!in_array($clo->DRPID,$prisidentIds)){
                array_push($data,$clo);
                $chld = $this->get_local_chapter_clo($clo->DRPID,$prisidentIds);
                $data = array_merge($data,$chld);
            }
        }
        return $data;
    }

    //找到学习官的城市分会
    public function find_chapter_city($drpId){

        $cloInfo = DB::table('memberdrp as a')
            ->leftJoin('memberinfo as b','b.MemNumber','=','a.MemNumber')
            ->select('a.ParentID','b.city','b.UserID')
            ->where('a.DRPID',$drpId)
            ->first();

        //检查该学习官是否已成为会长 如果已成为，则取分会
        $chapterPrisident = DB::table('chapter_prisident as a')
            ->leftJoin('chapter as b','b.');

        $chapterInfo = DB::table('chapter as a')
            ->leftJoin('region as b','b.region_id','=','a.city')
            ->select('a.chapter_name','b.region_name as cityName','a.city as chapterCity')
            ->where('city',$cloInfo->city)
            ->first();
        if($chapterInfo){
            return $chapterInfo;
        }elseif($cloInfo->ParentID > 0){
            return $this->find_chapter_city($cloInfo->ParentID);
        }else{
            $zongbu = new \stdClass();
            $zongbu->chapter_name = "上海总部";
            $zongbu->cityName = "上海";
            $zongbu->chapterCity = 0;
            return $zongbu;
        }

    }



    //找到分会下面的会员
    public function find_chapter_member(){
        ignore_user_abort();
        set_time_limit(0);
        $userId             = 9015;
        $memberInfo         = $this->get_next_member($userId,false);    //不包含学习官

        $zongbuchapterId    = 19;
        $addTime            = date_time();

        $chapterModel       = new ChapterModel();
        $chapters           = $chapterModel->get_chapters();
        $chapterCities      = [];
        $chapterIds         = [];
        foreach($chapters as $chapter){
            array_push($chapterCities,$chapter->city);
            array_push($chapterIds,$chapter->chapter_id);
        }

        do{

            //检查用户是否已经有了归属分会
            $userCity   = $memberInfo->city;
            $userId     = $memberInfo->UserID;
            $chapterMember = DB::table('chapter_member')->where('user_id',$userId)->first();
            if($chapterMember){
                goto loop;
            }

            //当前区域 是否 有分会
            $p = array_search($userCity,$chapterCities);
            if($p !== false)
            {
                $chapterId  = $chapterIds[$p];
            }
            else
            {
                $chapterId = 0;
            }

            if($memberInfo->ParentID > 0 && $chapterId == 0)
            {
                //跟着学习官的所属区域走
                $chapterDrpInfo = DB::table('memberdrp as a')
                    ->leftJoin('memberinfo as b','b.MemNumber','=','a.MemNumber')
                    ->leftJoin('chapter_drp as d','d.user_id','=','b.UserID')
                    ->select("d.chapter_id")
                    ->where('a.DRPID',$memberInfo->ParentID)
                    ->first();
                $chapterId = $chapterDrpInfo ? $chapterDrpInfo->chapter_id : $zongbuchapterId;
            }
            elseif($chapterId == 0) //没有学习官 直接归属总部
            {
                $chapterId = $zongbuchapterId;
            }


            //关联分会
            $data = [
                'chapter_id'    => $chapterId,
                'user_id'       => $userId,
                'is_delete'     => 0,
                'add_time'      => $addTime
            ];
            DB::table('chapter_member')->insert($data);

            loop:
            $memberInfo = $this->get_next_member($userId,false);
        }while($memberInfo);

        die("end");
    }



    private function mictime(){
        echo microtime()."<br/>";
    }

    /**
     * 获得下一个会员
     * @param integer $userId 用户ID 查找的是大于这个用户的会员
     * @param boolean $hasDrp 是否包含学习官
     * @param boolean $onlyPersonalVip 是否仅仅是个人会员
     * @return Object
     * */
    public function get_next_member($userId,$hasDrp=true,$onlyPersonalVip=false){

        /**
         * 如何定义仅仅是企业会员
         * 1.用户是会员  并且存在个人时间
         *
         *
         * */

        $memberInfo = false;
        while(!$memberInfo){
            //找到这个人
            $memberInfo = DB::table("memberinfo")
                ->select('city','UserID','MemNumber')
                ->where('UserID','>',$userId)
                ->where('States',1)
                ->where('DeleteMark',1)
                ->orderBy('UserID')->first();

            if($memberInfo){

                $userId = $memberInfo->UserID;
                $drpInfo = DB::table('memberdrp')
                    ->select('ParentID','DRPLevel')
                    ->where('MemNumber',$memberInfo->MemNumber)
                    ->where('DeleteMark',1);

                if($hasDrp == false){
                    $drpInfo->where('DRPLevel',"<>",'1');
                }

                $drpInfo = $drpInfo->first();

                if($drpInfo){ //存在表里面

                    $memberInfo->ParentID = $drpInfo->ParentID;
                    if($hasDrp == false && $drpInfo->DRPLevel == 1){ //如果不取学习官但是目前又是学习官 继续查找
                        $memberInfo = false;
                    }
                }else{
                    $memberInfo->ParentID = 0;
                }

            }else{
                break;
            }
        };

        return $memberInfo;
    }



    public function renzen(){

        return view('other/weixin-subscribe');

        $weixinService = new WeixinServiceController();
        $app    = $weixinService->get_weixin_app();

        $token  = $app->access_token;


        $token  = $token->getToken();
        return $token;
    }


    //检查学习官的二维码
    public function check_clo_erweima()
    {

        $sql = "SELECT a.DRPID,b.MemNumber,b.YourName
              FROM memberdrp a
              LEFT JOIN memberinfo b ON  b.MemNumber = a.MemNumber
              WHERE a.DeleteMark=1
              AND a.DRPLevel = 1
              AND b.DeleteMark = 1 ";
        $drps   = DB::select($sql);

        $qrcode     = new BaconQrCodeGenerator;
        $memnumbers = [];

        foreach($drps as $drp)
        {
            //$file = "uploads/qrcode/".$drp->MemNumber.".png";
            $file = public_path('/uploads/qrcode/' . $drp->MemNumber . '.png');
            //if(!file_exists($file))
            //{
                $url = 'http://wx.laohoulundao.com/parent/' . $drp->DRPID . '.html';
                $qrcode->format('png')->size(300)->generate($url, $file);
                array_push($memnumbers,$drp);
            //}
        }

        dd($memnumbers);

    }



    //批量压缩文件
    public function yasuo_img(Request $request){
        $dir    = $request->input('dir');
        if(!file_exists($dir))
        {
            return "文件夹{$dir}不存在";
        }
        change_img_size(public_path($dir),500,null,50);
        return "压缩完毕";
    }



    //给过期用户赠送三个月时间并发送短信提示
    public function yanchang_shijian()
    {

        $sql = "SELECT a.UserID,a.UserName,a.YourName,a.MemEndTime ,a.personal_end_time '个人时间'
                        FROM 			memberinfo a
                        LEFT JOIN company_user h ON h.user_id = a.UserID
                        LEFT JOIN company 	m ON m.company_id = h.company_id
                        WHERE 		a.DeleteMark = 1
                        AND 		a.States = 1
                        AND 		a.MemEndTime = '2018-01-06'
                        AND			a.MemEndTime <> ''
                        AND 		(h.is_delete IS NULL OR h.is_delete = 0)
                        AND			m.company_name is NULL
                      GROUP BY a.UserID,h.company_id";

        $users  = DB::select($sql);
        $msgModel       = new MobileMassege();
        $memberModel    = new MemberModel();

        foreach($users as $u)
        {
            $msgModel->mobile   = $u->UserName;
            $msg    = "亲爱的{$u->YourName}！您加入教导读书会已有1年时间，为了答谢首批会员，现将您的会员时间有效期延至2018年01月06日。祝您节日快乐！";
            $data   = [
                'UserID'    =>  $u->UserID,
                'MemEndTime'=>  '2018-01-06 00:00:00',
                'personal_end_time' => '2018-01-06 00:00:00'
            ];
            $memberModel->update_member_info($data);
            $msgModel->send_msg($msg);
        }
    }




    //删除重复的会员
    public function delete_repeat_member()
    {

        $companyModel   = new CompanyModel();
        $memberModel    = new MemberModel();

        //第一次被删除的用户的所有ID
        //$us = [7989,13553,11160,5955,8430,13602,11985,690,10085,8169,189,6099,7964,13964,2920,13482,13289,6826,9190,3540,2918,7982,8562,8160,7276,10001,7960,7007,7451,2917,7016,13273,5846,2073,11334,13574,13291,10023,7988,7976,7987,4965,5601,7867,10018,10007,10008,10021,11401,7456,2040,1549,5667,5645,5646,8132,12463,7977,1239,7939,14640,12478,7993,7978,7947,1077,13292,6930,5629,12518,11857,15904,7961,12480,13817,11986,10013,5633,7858,15933,5968,7968,5211,12422,12526,7984,7870,13852,7521,7453,10076,5906,5621,7985,5650,7866,13309,6548,15876,2915,7981,5620,5632];

        $sql = "SELECT
                GROUP_CONCAT(States) status,
                GROUP_CONCAT(UserID) userId,
                UserName mobile,
                GROUP_CONCAT(YourName) `name`,
                GROUP_CONCAT(MemNumber)  num
                from memberinfo
                WHERE DeleteMark = 1 
                AND UserName != '' 
                GROUP BY UserName 
                HAVING COUNT(*) > 1 ";
        $members    = DB::select($sql);

        //检查后者有读书改进计划的

        $users  = [];
        foreach($members as $member)
        {
            $userIds    = explode(',',$member->userId);
            $nums       = explode(',',$member->num);
            $status     = explode(',',$member->status);

            $user       = [];
            foreach($userIds as $key=> $id)
            {
                $singleUser = [
                    'id'    =>$userIds[$key],
                    'num'   =>$nums[$key],
                    'mobile'=>$member->mobile,
                    'status'=>$status[$key]
                ];
                array_push($user,$singleUser);
            }
           // uasort($user,function($x,$y){return $x > $y;});
            array_push($users,$user);
        }

        //return $users;

        foreach($users as $user) //所有用户
        {
            $isDrp = false;
            $i = 1;
            $total = count($user);
            $upUid = 0;
            $upMem = "";

            foreach($user as $u) //某个重复的用户
            {
                //1.检查是否有学习官
                $uid    = $u['id'];
                $unum   = $u['num'];

                $drp = DB::table('memberdrp')
                    ->where('MemNumber',$unum)
                    ->where('DeleteMark',1)
                    ->first();

                if($drp)
                {
                    if($drp->ParentID == 0)
                    {
                        $drpDelete = true;
                    }
                    if($drp->DRPLevel == 1)
                    {
                        $isDrp = true;
                    }
                }else{
                    $drpDelete = true;
                }

                //没激活 没学习官 不是最后一个 直接删除
                if($u['status'] == 0 && $drpDelete == true && $i < $total)
                {
                    $this->delete_user($uid);
                    $i++;
                    continue;
                }


                //3.检查是否有读书改进计划
                $sump = DB::table('booksumup')->where('MemNumber',$unum)->get();

                //4.是否加入了某家公司 多家公司
                $comuser = DB::table('company_user')->where('is_delete',0)->where('user_id',$uid)->get();

                //5.是否加入了某个读书会
                $readUser = DB::table('read_party_member')->where('is_delete',0)->where('user_id',$uid)->get();

                //如果不是最后一个人 以上记录都没有  直接删除
                if(!$sump && !$comuser && !$readUser && $drpDelete)
                {
                    $this->delete_user($uid);
                    $i++;
                    continue;
                }



                //如果已有学习官角色  则以学习官角色为保留
                if(($isDrp || $sump || $comuser || $readUser) && $upUid == 0 )
                {
                    //加入读书会
                    $upUid = $uid;
                    $upMem = $unum;
                }
                //已经有了确定修改的对象  并且不是最后一个  则将后面的信息改为前面的信息
                elseif(($isDrp || $sump || $comuser || $readUser) && $upUid > 0)
                {
                    if(true)
                    {
                        //检查被修改的用户是否已在将要修改的数据中
                        foreach($sump as $s)
                        {
                            $sump1 = DB::table('booksumup')
                                ->where('MemNumber',$upMem)
                                ->where('BookID',$s->BookID)
                                ->first();
                            if(!$sump1)
                            {
                                DB::table('booksumup')
                                    ->where('SumUpID',$s->BookID)
                                    ->update(['MemNumber'=>$upMem]);
                            }
                        }

                        //遍历加入的多家公司
                        foreach($comuser as $cu)
                        {
                            $comuser1 = DB::table('company_user')
                                ->where('company_id',$cu->company_id)
                                ->where('department_id',$cu->department_id)
                                ->where('read_party_id',$cu->read_party_id)
                                ->where('is_delete',0)
                                ->where('user_id',$upUid)
                                ->first();

                            if(!$comuser1) //没有在这样的公司
                            {
                                DB::table('company_user')
                                    ->where('company_user_id',$cu->company_user_id)
                                    ->update(['user_id'=>$upUid]);
                                $memberModel->change_member_endtime($upUid);
                            }
                        }

                        //某个号码加入的所有读书会
                        foreach($readUser as $ru)
                        {
                            //检查正确的号码是否加入
                            $readUser1 = DB::table('read_party_member')
                                ->where('read_party_id',$ru->read_party_id)
                                ->where('department_id',$ru->department_id)
                                ->where('user_id',$upUid)
                                ->where('is_delete',0)
                                ->first();

                            //正确的号码没有加入，则将错误的改为正确的
                            if(!$readUser1)
                            {
                                DB::table('read_party_member')
                                    ->where('read_user_id',$ru->read_user_id)
                                    ->update(['user_id'=>$upUid]);
                            }
                        }
                    }
                    //把用户删除
                    $this->delete_user($uid);
                }
                elseif($upUid > 0)
                {
                    $this->delete_user($uid);
                }
                $i++;
            }
        }

        //return $users;
    }


    //删除用户
    public function delete_user($userId)
    {
        DB::table('memberinfo')->where('UserID',$userId)->update(['DeleteMark'=>0]);
    }


    //设置学习官所属的分会
    public function set_chapter_of_clo($request)
    {

        $sql = "SELECT b.UserID,b.city,b.YourName
              FROM memberdrp a
              LEFT JOIN memberinfo b ON b.MemNumber = a.MemNumber
              WHERE a.DeleteMark  = 1
              AND   b.DeleteMark  = 1
              AND   b.States      = 1
              AND   a.DRPLevel = 1";
        $drps   = DB::select($sql);
        $memberModel    = new MemberModel();
        foreach($drps as $drp)
        {
            $userId     = $drp->UserID;
            $chapterId  = $this->get_chapter_of_drp($userId,$memberModel);//找到用户所在分会
            $tempInfo   = DB::table('chapter_drp')->where('user_id',$userId)->where('is_delete',0)->first();
            if($tempInfo)
            {
                DB::table('chapter_drp')
                    ->where('chapter_drp_id',$tempInfo->chapter_drp_id)
                    ->update(['chapter_id'=>$chapterId]);
            }
            else{
                debug_log('未找到分会的学习官','userId='.$userId.",chapterId=".$chapterId);
            }
        }
        return [$drps];
    }


    /**
     * 获取学习官所属的分会区域
     * */
    private function get_chapter_of_drp($userId,MemberModel $memberModel){

        //优先看自己是不是发起人
        $prisident = DB::table('chapter_prisident')
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->where('prisident_type','Z')
            ->first();

        if($prisident)
        {
            return $prisident->chapter_id;
        }

        $userInfo   = $memberModel->get_member_info_by_id($userId);
        $city       = $userInfo->city;
        $chapter    = $this->get_chapter_by_city($city);
        if($chapter)
        {

            return $chapter->chapter_id;
        }

        $drpModel   = new DrpModel();
        $drpInfo    = $drpModel->get_member_drp_info($userId);
        $parentId   = $drpInfo->ParentID;
        if($parentId == 0)
        {
            return 5001;
        }

        $drpInfo    = $drpModel->get_drp_info_by_drpid($parentId);
        $userId     = $drpInfo->UserID;
        return $this->get_chapter_of_drp($userId,$memberModel);
    }


    /**
     * 设置用户的城市归属地
     * */
    public function set_member_city(Request $request)
    {

        $mobile = $request->input('mobile');
        $regionService = new Region();

        //$cityInfo = $regionService->get_mobile_city_info($mobile);


        $sql = "SELECT k.* FROM (
                    SELECT
                    a.UserID,
                    a.UserName,
                    a.YourName,
                    LEFT(a.personal_end_time,10)  perEndTime,
                    LEFT(a.MemEndTime,10) endTime,
                    a.RegisterType,
                    d.company_id,
                    a.city

                    FROM memberinfo a
                    LEFT JOIN company_user d ON d.user_id = a.UserID AND d.is_delete = 0


                    WHERE  a.DeleteMark = 1
                    AND a.States = 1
                    AND a.personal_end_time <> ''
                    GROUP BY a.UserID
        ) as k

        WHERE ((k.company_id IS NOT NULL  AND k.perEndTime <> k.endTime) OR k.company_id is NULL ) AND k.city = 0";

        $mobiles = [];
        $members = DB::select($sql);
        foreach($members as $mem)
        {

            $mobile = $mem->UserName;
            if(!preg_match('/1\d{10}/',$mobile)){
                array_push($mobiles,$mobile);
                continue;
            }


            //获取用户城市信息
            $cityInfo = $regionService->get_mobile_city_info($mobile);

            if(!$cityInfo){
                //dd('没有找到城市');
                array_push($mobiles,$mobile);
                continue;
            }

            //验证手机号码
            $cityId = $cityInfo->region_id;
            DB::table('memberinfo')->where('UserName',$mobile)->update(['city'=>$cityId]);
        }
        dd($mobiles);
    }


    /**
     * 根据城市获得会长
     * */
    private function get_chapter_by_city($city)
    {
        $chapter = DB::table('chapter')->where('is_delete',0)->where('city',$city)->first();
        return $chapter;
    }


    public function set_member_chapter()
    {
        $loop   = true;
        $memberModel    = new MemberModel();
        $drpModel       = new DrpModel();
        $time           = date_time();
        $begin          = 0;
        while($loop)
        {
            $sql = "SELECT k.* FROM (
                        SELECT
                        a.UserID,
                        a.MemNumber,
                        a.UserName,
                        a.YourName,
                        LEFT(a.personal_end_time,10)  perEndTime,
                        LEFT(a.MemEndTime,10) endTime,
                        a.RegisterType,
                        d.company_id,
                        a.city

                        FROM memberinfo a
                        LEFT JOIN company_user d ON d.user_id = a.UserID AND d.is_delete = 0


                        WHERE  a.DeleteMark = 1
                        AND a.States = 1
                        AND a.personal_end_time <> ''
                        GROUP BY a.UserID
            ) as k

            WHERE (k.company_id IS NOT NULL  AND k.perEndTime <> k.endTime) OR k.company_id is NULL
            LIMIT {$begin},100 ";
            $members = DB::select($sql);
            $begin += 100;

            if(!$members){
                $loop = false;
                break;
            }

            foreach($members as $mem)
            {
                $chapterId  = $this->get_chapter_by_city($mem->city);

                if(!$chapterId) //本地没有  根据学习官来找
                {
                    $num = $mem->MemNumber;
                    $sql = "SELECT h.chapter_id FROM memberdrp a
                              LEFT JOIN memberdrp b ON  b.DRPID = a.ParentID
                              LEFT JOIN memberinfo d ON  d.MemNumber = b.MemNumber
                              LEFT JOIN chapter_drp_copy h ON h.user_id = d.UserID
                              WHERE a.DeleteMark = 1
                              AND a.MemNumber = '{$num}'
                              AND b.DeleteMark = 1
                              AND h.is_delete = 0 ";
                    $chapter = DB::select($sql);

                    if(count($chapter) > 0)
                    {
                        $chapterId = $chapter[0]->chapter_id;
                    }
                    else{
                        $chapterId = 19;
                    }
                } else{
                    $chapterId = $chapterId->chapter_id;
                }

                $data = [
                    'chapter_id'    => $chapterId,
                    'user_id'       => $mem->UserID,
                    'is_delete'     => 0,
                    'add_time'      => $time
                ];

                DB::table('chapter_member')->insert($data);

            }
        }
    }


    public function down_chapter_member()
    {

        $chapterModel   = new \App\Models\V2\ChapterModel();
        //$chapters   = $chapterModel->get_chapters();
        $chapters = DB::table('chapter')->where('is_delete',0)->get();

        foreach($chapters as $ch)
        {
            $sql = "SELECT a.chapter_id,b.chapter_name,d.UserName,d.YourName,d.personal_end_time,d.MemEndTime,d.RegisterType,d.AddDate ,g.region_name
                    from  chapter_member_copy  a
                    LEFT JOIN  chapter b ON b.chapter_id = a.chapter_id
                    LEFT JOIN memberinfo d ON d.UserID = a.user_id
                    LEFT JOIN memberdrp h ON h.MemNumber = d.MemNumber
                    LEFT JOIN region g ON g.region_id = d.city

                    WHERE  a.chapter_id = $ch->chapter_id
                    #WHERE  a.chapter_id = 2
                    AND (h.DeleteMark = 1 || h.DeleteMark is NULL)
                    AND (h.DRPLevel = 2 || h.DRPLevel is null)
            ";

            $members = DB::select($sql);
            $members = object_to_array($members);
            $title = [["分会ID","分会名称","手机号","用户名","个人时间","截止时间","注册类型","注册时间","电话号码归属地"]];
            array_splice($members,0,0,$title);
            $name = $ch->chapter_name."-".$ch->chapter_id;
            Excel::create(iconv('UTF-8', 'GBK', $name),function($excel) use ($members){
                $excel->sheet('score', function($sheet) use ($members){
                    $sheet->rows($members);
                });
            })->store('xls');

        }
    }


    public function down_chapter_clo()
    {

        $chapters = DB::table('chapter')->where('is_delete',0)->get();

        foreach($chapters as $ch)
        {
            $sql = "SELECT d.chapter_name,b.UserName,b.YourName,h.region_name
                    FROM chapter_drp_copy a
                    LEFT JOIN memberinfo b ON b.UserID = a.user_id
                    LEFT JOIN chapter d ON d.chapter_id = a.chapter_id
                    LEFT JOIN region h ON  h.region_id = b.city
                    WHERE a.chapter_id = $ch->chapter_id ";

            $members = DB::select($sql);
            $members = object_to_array($members);
            $title = [["分会名称","手机号","用户名","电话号码归属地"]];
            array_splice($members,0,0,$title);
            $name = $ch->chapter_name."-学习官";
            Excel::create(iconv('UTF-8', 'GBK', $name),function($excel) use ($members){
                $excel->sheet('score', function($sheet) use ($members){
                    $sheet->rows($members);
                });
            })->store('xls');

        }
    }

    public function  getInfo(Request $request){
        $openId = $request->openid;
        $token  = $request->token;
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openId}&lang=zh_CN";

        $http = new Http();
        $info = $info = $http->send($url);
        $info = \GuzzleHttp\json_decode($info);
        return [$info];
    }



    public function mergeexcel()
    {

        $d1 = ['a1'=>'姓名','a2'=>'性别','a3'=>'职务','a4'=>'手机','a5'=>'公司','f'=>''];
        $db = DB::table('www_w');
        //$this->savedata($db,$d1);

        $data = [['a1','a2','a3','a4','a5']];

        $dir = scandir('qimeili');

        foreach($dir as $f)
        {
            if(strlen($f) < 3)
            {
                continue;
            }


            Excel::load('qimeili/'.$f,function($reader) use (&$data,$f,$db){
                $i = $reader->all();
                dd($i);
                if(!$i)
                {
                    dd($i);
                }


                    $data = [];
                    foreach($i as $k)
                    {

                        dd($k->a1);
                        $k1 = $k;
                        if($k1 && $k1->a1){
                            $d = [
                                'a1'=>$k1->a1,
                                'a2'=>$k1->a2,
                                'a3'=>$k1->a3,
                                'a4'=>$k1->a4,
                                'a5'=>$k1->a5,
                                'f'=>$f
                            ];


                            //array_push($data,$d);
                            $this->savedata($db,$d);
                        }
                    }
            });



//
//            $name = "1/表格-".$f."-".date('y-m-d-H-i');
//            Excel::create(iconv('UTF-8', 'GBK', $name),function($excel) use ($data){
//                $excel->sheet('score', function($sheet) use ($data){
//                    $sheet->rows($data);
//                });
//            })->store('xls');
//


        }

      /*  $name = "表格-".date('y-m-d-H-i');
        Excel::create(iconv('UTF-8', 'GBK', $name),function($excel) use ($data){
            $excel->sheet('score', function($sheet) use ($data){
                $sheet->rows($data);
            });
        })->store('xls');*/


        return $data;
    }


    public function savedata($db,$data)
    {
        $db->insert($data);
    }


    //给有读书会的公司添加一个未分组的部门  以把所有未分组的用户都加入到里面
    public function add_empty_department()
    {
        //DB::beginTransaction();
        //1 所有读书会
        //$sql = "SELECT company_id from company where is_delete = 0 AND  company_id = 9";
        $sql = "SELECT company_id from company where is_delete = 0";
        $companys   = DB::select($sql);

        foreach($companys as $com)
        {

            //公司的所有部门
            $sql = "SELECT * FROM company_department
                    WHERE  company_id = $com->company_id AND  is_delete = 0 AND read_party_id = 0";
            $parts = DB::select($sql);


            //获取公司下的所有读书会
            $sql = "SELECT * FROM read_party where company_id = $com->company_id AND  DeleteMark = 1";
            $reads = DB::select($sql);

            foreach($reads as $read)
            {
                //将没有读书会的部门归属到第一个读书会下面
                DB::table('company_department')
                    ->where('company_id',$read->company_id)
                    ->where('read_party_id',0)
                    ->where('is_delete',0)
                    ->update(['read_party_id'=>$read->ReaParID]);

                //将部门添加到每个读书会
                foreach($parts as $part)
                {
                    //检查当前读书会是否有该部门
                    $info = DB::table('company_department')
                        ->where('company_id',$part->company_id)
                        ->where('read_party_id',$read->ReaParID)
                        ->where('department_name',$part->department_name)
                        ->where('is_delete',0)
                        ->first();
                    if($info)
                    {
                        continue;//有  下一个部门
                    }

                    //没有 插入
                    $np = [
                        'company_id'        =>$part->company_id,
                        'read_party_id'     =>$read->ReaParID,
                        'department_name'   =>$part->department_name
                    ];
                    DB::table('company_department')->insert($np);
                }


                //加入一个未分组部门
                //没有 插入
                //检查有没有未分组部门
                $empDp = DB::table('company_department')
                    ->where('company_id',$read->company_id)
                    ->where('read_party_id',$read->ReaParID)
                    ->where('department_name','未分组')
                    ->first();
                if($empDp)
                {
                    $newDpId = $empDp->department_id;
                }
                else
                {
                    $np = [
                        'company_id'    => $read->company_id,
                        'read_party_id' => $read->ReaParID,
                        'department_name'=>'未分组'];
                    $newDpId = DB::table('company_department')->insertGetId($np);
                }

                //将属于读书会  但 没有部门的会员加入到未分组中
                $sql = "SELECT
                        m.read_user_id,
                        mi.UserID,
                        mi.YourName,
                        p.ReaParID,
                        p.ReaParName,
                        cd.department_id,
                        cd.department_name,
                        com.company_id,
                        com.company_name,
                        cu.company_user_id
                        FROM read_party_member m
                        LEFT JOIN read_party  p 			ON p.ReaParID   = m.read_party_id
                        LEFT JOIN company_user cu 			ON cu.company_id 	= p.company_id AND cu.user_id = m.user_id
                        LEFT JOIN company com 				ON com.company_id = p.company_id
                        LEFT JOIN company_department cd 	ON cd.department_id = cu.department_id
                        LEFT JOIN memberinfo mi 			ON mi.UserID 				= m.user_id
                        WHERE m.is_delete = 0
                        AND p.DeleteMark  = 1
                        AND cu.is_delete  = 0
                        AND com.is_delete = 0
                        AND mi.DeleteMark = 1
                        AND m.read_party_id = $read->ReaParID
                        ORDER BY m.user_id ";

                $noDepartUsers = DB::select($sql);

                foreach($noDepartUsers as $u)
                {

                    $dpId   = $u->department_id ? $u->department_id : $newDpId;

                    DB::table('company_user')
                        ->where('company_user_id',$u->company_user_id)
                        ->update(['department_id'=>$dpId]);

                    DB::table('read_party_member')
                        ->where('read_user_id',$u->read_user_id)
                        ->update(['department_id'=>$dpId]);

                }


            }
        }

        //每个读书会所属公司的部门
        return 'ok';
    }


    public function ali_sign()
    {

        $data = [
            "Format"=>"XML",
            "SignatureMethod"=>"HMAC-SHA1",
            "Action"=>"DescribeLiveSnapshotConfig",
            "AccessKeyId"=>"testid",
            "RegionId"=>"cn-shanghai",
            "ServiceCode"=>"live",
            "DomainName"=>"test.com",
            "AppName"=>"test",
            "SignatureNonce"=>"c2fe8fbb-2977-4414-8d39-348d02419c1c",
            "Version"=>"2016-11-01",
            "SignatureVersion"=>"1.0",
            "Timestamp"=>"2017-06-14T09:51:14Z",
        ];
        ksort($data);
        $str    = http_build_query($data);
        $str    = "GET" . "&" . urlencode("/") . "&" . urlencode($str);
        $accesskey = "testsecret&";
        $str    = hash_hmac('sha1',$str,$accesskey,true);
        $sign   = base64_encode($str);

    }

    /**
     * 腾讯签名
     * */
    public function tencent_sign()
    {


        require app_path("Libs/Tencent/TimRestApi.php");

        #读取app配置文件
        $filename 		=  app_path("Libs/Tencent/TimRestApiConfig.json");
        $json_config 	= file_get_contents($filename);
        $app_config 	= json_decode($json_config, true);
        $sdkappid 		= $app_config["sdkappid"];
        $identifier 	= $app_config["identifier"];

        $private_pem_path = $app_config["private_pem_path"];
        $user_sig 		= $app_config["user_sig"];

        $tencentPath    = dirname(app_path(''))."/zhengshu/tencent/";
        //$private_pem_path   = $tencentPath."private_ec.pem";
        $private_pem_path   = $tencentPath."private_key";

        //独立模式
        if(!file_exists($private_pem_path))
        {
            echo "私钥文件不存在, 请确保TimRestApiConfig.json配置字段private_pem_path正确\n";
            return;
        }

        $api = createRestAPI();
        $api->init($sdkappid, $identifier);



        /**
         * 获取usersig
         * 36000为usersig的保活期
         * signature为获取私钥脚本，详情请见 账号登录集成 http://avc.qcloud.com/wiki2.0/im/
         */
        if(is_64bit()){
            if(PATH_SEPARATOR==':'){
                $signature = $tencentPath."signature/linux-signature64";
            }else{
                $signature = $tencentPath."signature\\windows-signature64.exe";
            }
        }else{
            if(PATH_SEPARATOR==':')
            {
                $signature = $tencentPath."signature/linux-signature32";
            }else{
                $signature = $tencentPath."signature\\windows-signature32.exe";
            }
        }


        $signature  = dirname(app_path(''))."/zhengshu/tencent/tls_licence_tools";
        $userSig    = $api->generate_user_sig($identifier, '36000', $private_pem_path, $signature);
        $groupTime  = "zhangweixi".time();
        $msg        = $api->group_create_group('Public',$groupTime,'shidaoadmin');

        if(count($msg)  == 0)
        {
            dd('返回信息错误');
        }

        return $msg;




        $api    =   new TLSSigAPI();
        //$api->SetAppid(1400052639);
        $api->SetAppid(1400001052);
        $ecKeyFile  = dirname(app_path(''))."/zhengshu/tencent/private_ec.pem";
        //$private = file_get_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'ec_key.pem');
        $private    = file_get_contents($ecKeyFile);
        $api->SetPrivateKey($private);

        $pubKeyFile = dirname(app_path(''))."/zhengshu/tencent/public_key";
        //$public = file_get_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'public.pem');
        $public     = file_get_contents($pubKeyFile);

        //$api->SetPublicKey($public);
        $sig = $api->genSig('shidaoadmin');
        //$result = $api->verifySig($sig, 'reading4_account', $init_time, $expire_time, $error_msg);
        return $sig;
        var_dump($result);
        var_dump($init_time);
        var_dump($expire_time);
        var_dump($error_msg);

//        $result = $api->verifySig($sig, 'user2', $init_time, $expire_time, $error_msg);
//        var_dump($result);
//        var_dump($init_time);
//        var_dump($expire_time);
//        var_dump($error_msg);
    }



    public function wx_pay_test()
    {
        $wxService  = new WeixinServiceController();
        $app        = $wxService->get_weixin_app();
        $payment    = $app->payment;

        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => 'iPad mini 16G 白色',
            'detail'           => 'iPad mini 16G 白色',
            'out_trade_no'     => '1217752501201407033233368018',
            'total_fee'        => 5388, // 单位：分
            'notify_url'       => 'http://xxx.com/order-notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => 'oPF8hxOdJ6B-HJHNgb-3U3KQ6rUA', // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];
        $order = new Order($attributes);

        //$result = $payment->pay($order);
        $result = $payment->prepare($order);

        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS')
        {
            $prepayId = $result->prepay_id;
        }else{

            return apiData()->notice('下单失败');
        }

        $jsConfig   = $payment->configForPayment($prepayId);

        return view('test/api',['jsConfig'=>$jsConfig]);

    }



    /**
     * 读取错误日志
     * */
    public function showErrorLog(Request $request)
    {
        $file       = $request->input('file','');
        $contents   = [];
        $files      = [];
        $dir        = base_path('storage/logs');
        $page       = $request->input('page',1);
        $page       = $page < 1 ? 1 : $page;
        $perpage    = $request->input('perpage',100);

        if($file == '')
        {
            $files  = scandir($dir);
            foreach($files as $key => $file)
            {
                if(!preg_match('/.log$/',$file)){
                    unset($files[$key]);
                }
            }
            $type   = "files";
        }
        else
        {
            $file   = $dir . "/" .$file;
            $begin      = 0-($page*$perpage);
            $command    = "head -n $begin $file | tail -n $perpage";
            $command    = "less $file | grep ERROR";
            $result     = shell_exec($command);
            $contents   = explode(PHP_EOL,$result);
            array_unshift($contents,$command);

            $allContent = [];
            $single     = [];

            foreach($contents as $con)
            {
                if(!preg_match('/^#/',$con)){

                    array_push($allContent,$single);
                    $single = [];
                    array_push($single,$con);
                }
            }
            $contents = $allContent;
            $type   = "content";
        }

        return view('other/show-error-log',[
            'contents'      => $contents,
            'type'          => $type,
            'files'         => $files,
            'page'          => $page,
            'file'          => $request->input('file',''),
            'perpage'       => $perpage
        ]);
    }


    //测试Redis
    public function test_redis()
    {
        return Redis::get('name');

    }


    /**
     * 获得ID地址
     * */
    public function get_id_address(Request $request)
    {
        $ip     = \EasyWeChat\Payment\get_client_ip();
        $ipInfo = get_ip_address($ip);

        return $ipInfo->country;
    }




    public function company_to_person()
    {
        $wxservice  = new WeixinServiceController();
        $app        = $wxservice->get_weixin_app();
        $merchantPay= $app->merchant_pay;

        $merchantPayData = [
            'partner_trade_no' => str_random(16), //随机字符串作为订单号，跟红包和支付一个概念。
            'openid' => "oPF8hxOdJ6B-HJHNgb-3U3KQ6rUA", //收款人的openid
            'check_name' => 'NO_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
            're_user_name'=>'张维喜',     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
            'amount' => 100,  //单位为分
            'desc' => '企业付款',
            'spbill_create_ip' => \EasyWeChat\Payment\get_client_ip(),  //发起交易的IP地址
        ];
        $result = $merchantPay->send($merchantPayData);

        var_dump($result);
    }

    //rsa加密响应字段
    public function rsa_encrypt($str)
    {
        $pem    = dirname(app_path('')).'/zhengshu/rsa/public.pem';
        $pu_key = openssl_pkey_get_public(file_get_contents($pem));  //读取公钥内容
        $encryptedBlock = '';
        $encrypted = '';
        // 用标准的RSA加密库对敏感信息进行加密，选择RSA_PKCS1_OAEP_PADDING填充模式
        //   （eg：Java的填充方式要选 " RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING"）
        // 得到进行rsa加密并转base64之后的密文
        openssl_public_encrypt($str,$encryptedBlock,$pu_key,OPENSSL_PKCS1_OAEP_PADDING);
        $str_base64  = base64_encode($encrypted.$encryptedBlock);
        return $str_base64;
    }

    /**
     * 获取公钥
     * */
    public function get_rsa_key()
    {
        $wxservice  = new WeixinServiceController();
        $app        = $wxservice->get_weixin_app();
        $merchantPay= $app->merchant_pay;
        $content    = $merchantPay->get_public_key();
        $key        = $content->pub_key;
        $pem        = dirname(app_path('')).'/zhengshu/rsa/public.pem';
        file_put_contents($pem,$key);
    }
    /**
     * 企业转账到银行卡
     * */
    public function company_to_bank()
    {
        $wxservice  = new WeixinServiceController();
        $app        = $wxservice->get_weixin_app();
        $merchantPay= $app->merchant_pay;
        $trade = create_member_number();
        $merchantPayData = [
            'partner_trade_no'  => $trade,
            "enc_bank_no"       => $this->rsa_encrypt("6212262402033128048"),
            "enc_true_name"     => $this->rsa_encrypt("张维喜"),
            "bank_code"         => 1002,
            'amount'            => 1,
            'desc' => '企业付款',
        ];

        $result = $merchantPay->send_to_bank($merchantPayData);
        return [$result];
    }



    public function edit()
    {
        return view('test.edit');
    }

    //API接口
    public function upgrade_api_version(Request $request)
    {
        $v = $request->input('v',0);
        if($v == 0)
        {
            return "need api version:ep: v=3";
        }

        $new_v = $v + 1;
        $dir = app_path("Http/Controllers/Api/");
        $oldDir = $dir . "V" . $v;
        $newDir = $dir . "V" . $new_v;


        if(!file_exists($newDir))
        {
            mkdir($newDir);
        }

        $dirsource  = opendir($oldDir);
        $oldVersion = "App\\Http\\Controllers\\Api\\V".$v;
        $newVersion = "App\\Http\\Controllers\\Api\\V".$new_v;

        $oldModel   = "App\\Models\\V".$v;
        //$oldModel   = "App\\Models\\V2";
        $newModel   = "App\\Models\\V".$new_v;


        while($file = readdir($dirsource))
        {
            if(preg_match('/^\./',$file))
            {
                continue;
            }

            $oldFile = $oldDir."/".$file;
            $newFile = $newDir."/".$file;
            if(!file_exists($newFile))
            {
                copy($oldFile,$newFile);
            }
            $content = file_get_contents($newFile);
            $content = str_replace($oldVersion,$newVersion,$content);
            $content = str_replace($oldModel,$newModel,$content);
            file_put_contents($newFile,$content);
        }

        return 'ok, finished !';
    }


    //升级模型
    public function upgrade_model_version(Request $request)
    {
        $v = $request->input('v','');
        if($v == '')
        {
            return "need api version:ep: v=3";
        }

        $new_v = $v + 1;
        $dir = app_path("Models/");

        $oldDir = $dir . "V" . $v;
        $newDir = $dir . "V" . $new_v;

        if(!file_exists($newDir))
        {
            mkdir($newDir);
        }

        $dirsource  = opendir($oldDir);
        $oldVersion = "App\Models\V".$v;
        $newVersion = "App\Models\V".$new_v;


        while($file = readdir($dirsource))
        {
            if(preg_match('/^\./',$file))
            {
                continue;
            }

            $oldFile = $oldDir."/".$file;
            $newFile = $newDir."/".$file;
            if(!file_exists($newFile))
            {
                copy($oldFile,$newFile);
            }
            $content = file_get_contents($newFile);
            $content = str_replace($oldVersion,$newVersion,$content);
            file_put_contents($newFile,$content);
        }

        return 'ok, finished !';
    }


}


function read_all ($dir,array &$files){
    if(!is_dir($dir)) return false;

    $handle = opendir($dir);

    if($handle){
        while(($fl = readdir($handle)) !== false){
            $temp = $dir.DIRECTORY_SEPARATOR.$fl;
            //如果不加  $fl!='.' && $fl != '..'  则会造成把$dir的父级目录也读取出来
            if(is_dir($temp) && $fl!='.' && $fl != '..'){
                //echo '目录：'.$temp.'<br>';
                read_all($temp,$files);
            }else{
                if($fl!='.' && $fl != '..'){

                    //echo '文件：'.$temp.'<br>';
                    array_push($files,$temp);
                }
            }
        }
    }
}